﻿#include "chaoyinapi.h"
#define KEY "cysoft_2016"
#define Url "http://119.23.210.194:8083/Business/ProcedureOutQuery"
#define questMaxNum 2000  //每次批量请求的最大数
chaoyinAPI::chaoyinAPI()
{

    manager = new QNetworkAccessManager(this);
    pages = 1;

      //打开数据库
    goodsData = QSqlDatabase::addDatabase("QSQLITE", "sqlite");//dw_bs
    goodsData.setDatabaseName(".//goodsdata.db");

    if(!(goodsData.open()))
    {
        qDebug() << "open goodsdata.db error!\n";
        return;
    }
    xh = 0;
//    //创建对应的表格
//   creadTable(goodsGet);
//   creadTable(goodsPrice);
//   creadTable(goodsType);
//   creadTable(member);
//   creadTable(integral);
   // telnetGetChaoYinData(goodsType,pages,1000);

}



struct goodsInfo chaoyinAPI::goods_From_Bar(QString bar)
{
    //sqlite> SELECT * FROM COMPANY WHERE NAME LIKE 'Ki%';

    struct goodsInfo info;
    QSqlQuery sql_query_goodsMesg(goodsData);  //以条形码从数据库中获取商品信息
    QSqlQuery sql_query_goodsPrice(goodsData); //以商品编码从数据库中商品价格
    QSqlQuery sql_query_goodsType(goodsData); //以商品编码从数据库中商品类别
    QString goodsbar    = "select * from Goods where barcode = :bar";
    QString goodsPrice  = "select * from Price where bm = :bm";
    QString goodsType   = "select * from Type where bm = :bm_fl";
    sql_query_goodsMesg.prepare(goodsbar);
    sql_query_goodsPrice.prepare(goodsPrice);
    sql_query_goodsType.prepare(goodsType);
    sql_query_goodsMesg.bindValue(":bar",bar);
    if(!sql_query_goodsMesg.exec())
    {
        qDebug() << sql_query_goodsMesg.lastError();
    }
    else
    {
        while(sql_query_goodsMesg.next())
        {
            info.bincode =  sql_query_goodsMesg.value("bm").toString();
            info.barcode =  sql_query_goodsMesg.value("barcode").toString();
            info.name    =  sql_query_goodsMesg.value("mc").toString();
            info.goodsTypeBinCode = sql_query_goodsMesg.value("bm_fl").toString();

            //以商品编码从数据库中商品价格
            if(!info.bincode.isEmpty() || !info.bincode.isNull())
            {
                sql_query_goodsPrice.bindValue(":bm",info.bincode);
                if(!sql_query_goodsPrice.exec())
                {
                    qDebug() << sql_query_goodsMesg.lastError();
                }
                else
                {
                    while(sql_query_goodsPrice.next())
                    {
                        info.vipPrice = sql_query_goodsPrice.value("dj_hy").toDouble();
                        info.salePrice = sql_query_goodsPrice.value("dj_ls").toDouble();
                    }
                 }
            }
            //以商品类别编码从数据库中商品类别名称
            if(!info.goodsTypeBinCode.isEmpty() || !info.goodsTypeBinCode.isNull())
            {
                sql_query_goodsType.bindValue(":bm_fl",info.goodsTypeBinCode);
                if(!sql_query_goodsType.exec())
                {
                    qDebug() << sql_query_goodsType.lastError();
                }
                else
                {
                    while(sql_query_goodsType.next())
                    {
                       info.goodsType = sql_query_goodsType.value("mc").toString();
                    }
                 }
            }

        qDebug() <<" 商品编码 ："<< info.bincode<<" 条形码 ：" <<info.barcode<<" 商品名称 ：" <<info.name\
                 << "会员价格:" << QString::number(info.vipPrice )<< "销售价格: " << QString::number( info.salePrice)\
                 <<"商品类别:" << info.goodsType;
        }
    }
    return info;
}

void chaoyinAPI::goods_mesg()
{
    QByteArray data = reply->readAll();
    if(!data.isNull() || !data.isEmpty())
    goodsmesg_json(data);

}
void chaoyinAPI::on_readyRead()
{
    QByteArray data = reply->readAll();
     if(!data.isNull() || !data.isEmpty())
        member_xml(data);
}
void chaoyinAPI:: member_xml(QByteArray xmlData)
{
    QXmlStreamReader reader(xmlData);
    while(!reader.atEnd() && !reader.hasError())
    {
         reader.readNext();
        if(reader.isStartElement())
         {
             //查询积分的结果
             if (reader.name() == "IntegralQueryResult")
                {
                     QXmlStreamReader ResultXml(reader.readElementText());
                     while(!ResultXml.atEnd() && !ResultXml.hasError())
                     {
                          if(ResultXml.name() == "message")
                            qDebug() << "message:"<<ResultXml.readElementText();  //操作成功
                          else if(ResultXml.name() == "je_ye")
                          qDebug() << "金额:"<<ResultXml.readElementText();
                            else if(ResultXml.name() == "je_jf")
                            qDebug() << "积分:"<<ResultXml.readElementText();
                            else if(ResultXml.name() == "je_ye_czzs")
                            qDebug() << "赠送金额:"<<ResultXml.readElementText();


                          ResultXml.readNext(); //读取下一个标签
                     }
                }
          }else if (reader.isEndElement())qDebug("EndElement");     //结束标签
            else if(reader.isEndDocument())qDebug("endDocument\n");  //结束文档

    }
}

void chaoyinAPI::goodsmesg_json(QByteArray srcdata)
{
   // QString  Result Message Data{status,rList,outStr} Sign
   qDebug()<<"------------------数据解析-----------------";
  allData.append(srcdata);
   QJsonObject json_srcdata = QJsonDocument::fromJson(allData.data()).object();
   QString sign =  json_srcdata.value("Sign").toString();
   if(sign.isNull() || sign.isEmpty())return;
   qDebug() << srcdata.data();

   qDebug() << json_srcdata.value("Result").toString();
    //QString  messg= json_srcdata.value("Message").toString();
    QJsonObject Data  = json_srcdata.value("Data").toObject();
    int countStr =  Data.value("outStr").toString().toInt();

    QJsonArray goodsArry =  Data.value("rList").toArray();
    QJsonObject goods;
    int i;
    if(goodsArry.isEmpty())return;
    //从网络获取的数据解析后添加到数据库
    goodsData .transaction();  //开启事务
    for(i = 0;i <goodsArry.size();i++)
    {
        goods = goodsArry.at(i).toObject();
        addToSqlite(goods);
     //   qDebug()<<QString::number(i);
    }
    goodsData.commit();  //提交事务
    qDebug() << "inset succeed!";
    allData.clear();
    pages++;
    if(pages*questMaxNum<countStr)
    {
        telnetGetChaoYinData(begtype,pages,questMaxNum);
    }
     else if(0<(pages*questMaxNum-countStr) && (pages*questMaxNum-countStr)<questMaxNum)
    {
        telnetGetChaoYinData(begtype,pages,questMaxNum);
    }
}

/*
 * QJsonObject({"bm":"010200721","bm_gsjg":"1001","dj_hy":8.8000000000000007,
 * "dj_jh":4.2000000000000002,"dj_ls":8.8000000000000007,"dj_pf":8.5999999999999996,"dw_bs":1,"n_last":20908})
 */
void chaoyinAPI::addToSqlite(QJsonObject Goods)
{
    QString insert_sql;
    switch (begtype) {
    case goodsGet:
         insert_sql.append("insert into Goods values (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        break;
    case goodsPrice:
         insert_sql.append("insert into Price values (?, ?, ?, ?, ?, ?, ?,?)");
        break;
    case goodsType:
         insert_sql.append("insert into Type values (?, ?, ?,?)");
          break;
    case member:
         insert_sql.append("insert into member values (?, ?, ?,?)");
          break;
     case integral:
         insert_sql.append("insert into Integral values (?, ?, ?)");
         break;
    }

 QSqlQuery sql_query(goodsData);
 sql_query.prepare(insert_sql);


    //qDebug() << Goods.keys();
    foreach (QString keys, Goods.keys()) {
        if(!keys.compare("dj_pf")||!keys.compare("dj_hy") || !keys.compare("dj_jh") ||!keys.compare("dj_ls") ||!keys.compare("jf") )
        {
              double tmp = Goods.value(keys).toDouble();
              sql_query.addBindValue(tmp);
        }else if(!keys.compare("dw_bs")|| !keys.compare("n_last") )
        {
                int tmp =  Goods.value(keys).toInt();
                sql_query.addBindValue(tmp);
        }else
        {
              QString tmp =  Goods.value(keys).toString();
              sql_query.addBindValue(tmp);

        }


    }
    sql_query.exec();


}
// 总共35134条

/*
 * QJsonObject({"bm":"010200721","bm_gsjg":"1001","dj_hy":8.8000000000000007,
 * "dj_jh":4.2000000000000002,"dj_ls":8.8000000000000007,"dj_pf":8.5999999999999996,"dw_bs":1,"n_last":20908})
 */

/*
 * 请求报文：	proname=P_ds_get_spfl&proparam=0|1|2&sign=857AFD1822FE0256F7608E3FAC3FB70F
 * proname	string	存储过程名称	P_get_spfl
 * proparam	string	参数串	n_last|页号|每页记录条数
 * sign	string	签名
 */

void chaoyinAPI::telnetGetChaoYinData(BegType requistType)
{
    //创建对应的表格
    creadTable(requistType);
    telnetGetChaoYinData(requistType,1,questMaxNum);
}

void chaoyinAPI::telnetGetChaoYinData(BegType requistType, int pages, int num)
{

    QString proname;    // = "P_ds_get_sp_dj";
    QString proparam;   //= "1001|0|";
    QByteArray byte_array1;
    begtype = requistType;
    //
    switch (begtype) {
    case goodsGet:
        proparam.append("1001|0|"); // 1001为商店编号
        proname.append("P_ds_get_sp");
        break;
    case goodsPrice:
        proparam.append("1001|0|");
        proname.append("P_ds_get_sp_dj");
        break;
    case goodsType:
        proparam.append("0|");
        proname.append("P_ds_get_spfl");
         break;
    case member:
        proparam.append("0|");
        proname.append("P_ds_get_hy");
         break;
    case integral:
        proparam.append("0|");
        proname.append("P_ds_get_jf_flow");
        break;
    }
    //打包报文
    proparam.append(QString::number(pages ));
    proparam.append(QString("|"));
    proparam.append(QString::number(num ));
    byte_array1.append(QString("proname="));
    byte_array1.append(proname);
    byte_array1.append(QString("&proparam="));
    byte_array1.append(proparam);
    QString sign = unit.signWithMd5(byte_array1,KEY); //生成Md5
    byte_array1.append(QString("&sign="));
    byte_array1.append(sign);


//网络请求
    request.setUrl(QUrl(Url));
       request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");

    request.setHeader(QNetworkRequest::ContentLengthHeader,byte_array1.size());
    reply = manager->post(request,byte_array1);
    connect(reply, SIGNAL(readyRead()), this, SLOT(goods_mesg()));

}

void chaoyinAPI::creadTable(BegType begtype)
{

   QSqlQuery sql_query(goodsData);
        QString create_sql;
        switch (begtype) {
        case goodsGet:
            create_sql.append("create table Goods (barcode  varchar(30),bm  varchar(30), bm_fl varchar(30),\
                                bm_pp  varchar(30),dw varchar(30),dw_bs int,gg  varchar(30),mc varchar(30),n_last int)");
            break;
        case goodsPrice:
          create_sql.append("create table Price ( bm varchar(30),bm_gsjg  varchar(30), dj_hy double,\
                            dj_jh double,售价 double,dj_pf double,dw_bs  int,n_last int)");
            break;
        case goodsType:
            create_sql.append("create table Type (bm  varchar(30),bm_parent  varchar(30),mc  varchar(30),n_last int)");
             break;
        case member:
            create_sql.append("create table member (bm  varchar(30),mc  varchar(30),n_last int, tel_yd varchar(30))");
             break;
        case integral:
            create_sql.append("create table Integral (bm  varchar(30),jf double,n_last int)");
             break;
        }

        sql_query.prepare(create_sql);
        if(!sql_query.exec())
        {
            qDebug() << "Error: Fail to create table." << sql_query.lastError();
        }
        else
        {
            qDebug() << "Table created!";
        }
}

int chaoyinAPI::commit_order()
{
    QJsonObject headObect;

    QJsonObject bodyObect;
    headObect.insert("dh",QString("10021"));
    headObect.insert("bm_gsjg",QString("10010"));
    headObect.insert("rq",unit.getCurrendate("yyyy-MM-dd hh:mm:ss"));
    headObect.insert("bm_hyk",QString(""));
    headObect.insert("rq_sh",QString(""));
    headObect.insert("rq_sh_time",QString(""));
    headObect.insert("gateway",QString(""));
    headObect.insert("phone_hy",QString(""));
    headObect.insert("shr",QString(""));
    headObect.insert(" shr_phone",QString(""));
    headObect.insert(" shr_address",QString(""));
    headObect.insert("name_logistics",QString(""));
    headObect.insert("dh_logistics",QString(""));
    headObect.insert("je_yf",0);
    headObect.insert("je_ys",0);
    headObect.insert("je_yh",0);
    headObect.insert("je_ss",1);
    headObect.insert("bz",QString(""));

    bodyObect.insert("dh",QString("10021"));
    bodyObect.insert("xh",1);
    bodyObect.insert("bm_sp",QString("10001"));
    bodyObect.insert("sl",1);
    bodyObect.insert("dj_hs",1);
    bodyObect.insert("dw_bs",1);
    bodyObect.insert(" je_zk",0);

    QJsonObject  jsondata;
    jsondata.insert("head",QJsonValue(headObect));
    jsondata.insert("body",QJsonValue(bodyObect));
    QJsonDocument document;
    document.setObject(jsondata);
    QByteArray byte_array = document.toJson(QJsonDocument::Compact);
    QString json_str(byte_array);

    QByteArray bytedata;
    bytedata.append(QString("orders="));
    bytedata.append(json_str);

    QString sign = unit.signWithMd5(bytedata,KEY); //生成Md5
    bytedata.append(QString("&sign="));
    bytedata.append(sign);
    qDebug()<<bytedata;
return 0;
}

void chaoyinAPI::integralQuery(int member)
{
    QString jsonParam;
    jsonParam.append("{id_hyk:'");
    jsonParam.append(QString::number(member));
    jsonParam.append("'}");
    requstMember(jsonParam);
}

void chaoyinAPI::BalanceQuery(int id, QString password)
{
    //网络请求
QString jsonParam;
jsonParam.append("{id_czk:'");
jsonParam.append(QString::number(id));
jsonParam.append("',password:'");
jsonParam.append(password);
jsonParam.append("'}");
   requstMember(jsonParam);
}
void chaoyinAPI::requstMember(QString jsonParam)
{
   QFile file("my2.xml");
    QString menberUrl = "http://119.23.210.194:8083/Services/CardService.asmx";

    if (!file.open(QFile::WriteOnly | QFile::Text))
    {
        qDebug() << "Error: cannot open file";
        return ;
    }
    file.resize(0);
    QXmlStreamWriter stream(&file);
    stream.setAutoFormatting(true);
    stream.writeStartDocument(); //      ?xml version="1.0" encoding="utf-8"?

     stream.writeStartElement("soap:Envelope");
     stream.writeAttribute("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance");
      stream.writeAttribute("xmlns:xsd","http://www.w3.org/2001/XMLSchema");
      stream.writeAttribute(" xmlns:soap","http://schemas.xmlsoap.org/soap/envelope/");
         stream.writeStartElement("soap:Body");
             stream.writeStartElement("IntegralQuery");
             stream.writeAttribute(" xmlns","http://tempuri.org/");
                 stream.writeStartElement("user");
                 stream.writeTextElement("id_gsjg","1");
                 stream.writeTextElement("bm_user","1");
                 stream.writeTextElement("password","");
                 stream.writeTextElement("checkcode","69344114cca71881f5899304df9a4437");
                 stream.writeTextElement("mac","00-16-96-0E-C0-3A");
                 stream.writeTextElement("version","20160701");
                 stream.writeEndElement();
                     stream.writeTextElement("jsonParam",jsonParam  );     //标价金额,单位为分

     stream.writeEndElement();
         stream.writeEndElement();
             stream.writeEndElement();

     stream.writeEndElement();//结束bady
     stream.writeEndDocument();  //结束文档
    file.close();
    if (!file.open(QFile::ReadOnly | QFile::Text))
    {
        qDebug() << "Error: cannot open file";
        return ;
    }
   QByteArray postdata = file.readAll();
    qDebug() << postdata;
    request.setUrl(QUrl(menberUrl));
       request.setRawHeader("Content-Type", "text/xml");
    reply = manager->post(request,postdata);
    connect(reply, SIGNAL(readyRead()), this, SLOT(on_readyRead()));
}
void chaoyinAPI::BalanceCost(int id, float je_xf, QString dh, QString password)
{
   //格式:{xh:'1',id_czk:'1',je_xf:'-1',je_zs_xf:'-1',dh:'test12345699',password:'123456',sign:'65715798504638f7af52ddb77a71183f''}
    xh +=1; //规定每次加1
    QString key = "s23dfsdfsaf23df5756tyf";
    QString jsonParam;
    jsonParam.append("{xh:");
    jsonParam.append("'");
    jsonParam.append(QString::number(xh));
    jsonParam.append("'");

    jsonParam.append(",id_czk:");
    jsonParam.append("'");
    jsonParam.append(QString::number(id));
    jsonParam.append("'");

    jsonParam.append(",je_xf:");
    jsonParam.append("'");
    jsonParam.append(QString::number(je_xf));
    jsonParam.append("'");

    jsonParam.append(",je_zs_xf:");
    jsonParam.append("'");
    jsonParam.append(QString::number(je_xf));
    jsonParam.append("'");

    jsonParam.append(",dh:");
    jsonParam.append("'");
    jsonParam.append(dh);
    jsonParam.append("'");

    jsonParam.append(",password:");
    jsonParam.append("'");
    jsonParam.append(password);
    jsonParam.append("'");

    QByteArray byte_array;
    QString signStr = password+dh+QString::number(id)+key+QString::number(je_xf)+QString::number(je_xf);
    byte_array.append(signStr);
    QByteArray hash_byte_array = QCryptographicHash::hash(byte_array, QCryptographicHash::Md5);
    QString md5 = hash_byte_array.toHex();
    requstMember(jsonParam);
    jsonParam.append(",sign:");
    jsonParam.append("'");
    jsonParam.append(md5);
    jsonParam.append("'}");

    requstMember(jsonParam);
}
